package org.jjche.swagger.property.plugin;

import cn.hutool.core.util.StrUtil;
import io.swagger.annotations.ApiParam;
import org.jjche.common.annotation.Dict;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.ParameterBuilderPlugin;
import springfox.documentation.spi.service.contexts.ParameterContext;
import springfox.documentation.swagger.common.SwaggerPluginSupport;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * <p>
 * swagger枚举入参定义
 * 在ApiParam参数定义枚举
 * </p>
 *
 * @author miaoyj
 * @version 1.0.0-SNAPSHOT
 * @since 2020-07-09
 */
@SuppressWarnings(value = "all")
public class EnumParameterBuilderPlugin implements ParameterBuilderPlugin {

    /**
     * {@inheritDoc}
     */
    @Override
    public void apply(ParameterContext context) {
        Optional<ApiParam> apiParam = context.resolvedMethodParameter().findAnnotation(ApiParam.class);
        if (apiParam.isPresent()) {
            ApiParam annotation = (ApiParam) apiParam.get();
            Class<?> type = context.resolvedMethodParameter().getParameterType().getErasedType();
            if (Dict.class.isAssignableFrom(type)) {
                Object[] enumConstants = type.getEnumConstants();
                List<String> displayTexts =
                        Arrays.stream(enumConstants)
                                .filter(Objects::nonNull)
                                .map(item -> {
                                    Dict dict = ((Dict) item);
                                    return StrUtil.format("{}:{}", dict.getCode(), dict.getText());
                                }).collect(Collectors.toList());
                String desc = annotation.value() + "(" + String.join(";", displayTexts) + ")";
                context.requestParameterBuilder()
                        .description(desc);
            }
        }
    }


    /**
     * {@inheritDoc}
     */
    @Override
    public boolean supports(DocumentationType delimiter) {
        return SwaggerPluginSupport.pluginDoesApply(delimiter);
    }
}
